package com.useeinfo.oa.open.admin.repair;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.useeinfo.framework.sugar.data.QueryParam;
import com.useeinfo.framework.sugar.data.SelectVO;
import com.useeinfo.framework.sugar.func.excel.ExcelExport;
import com.useeinfo.framework.sugar.func.file.FileUtils;
import com.useeinfo.framework.sugar.tools.AliJsonObjectCover;
import com.useeinfo.framework.sugar.tools.Configuration;
import com.useeinfo.framework.sugar.tools.DateTimeUtils;
import com.useeinfo.framework.sugar.tools.StringConverters;
import com.useeinfo.oa.common.config.ExcelExportMap;
import com.useeinfo.oa.common.utils.CommonUtils;
import com.useeinfo.oa.common.utils.ResultUtil.ResultDto;
import com.useeinfo.oa.common.utils.ResultUtil.ResultUtil;
import com.useeinfo.oa.modules.base.biz.*;
import com.useeinfo.oa.modules.base.entity.*;
import com.useeinfo.oa.modules.repair.biz.RepairLevelBiz;
import com.useeinfo.oa.modules.repair.biz.RepairOrderBiz;
import com.useeinfo.oa.modules.repair.biz.RepairOrderLogBiz;
import com.useeinfo.oa.modules.repair.biz.TroubleCatBiz;
import com.useeinfo.oa.modules.repair.entity.RepairLevel;
import com.useeinfo.oa.modules.repair.entity.RepairOrder;
import com.useeinfo.oa.modules.repair.entity.RepairOrderLog;
import com.useeinfo.oa.modules.repair.enums.*;
import com.useeinfo.oa.modules.security.biz.OrganizationBiz;
import com.useeinfo.oa.modules.security.biz.SystemUserBiz;
import com.useeinfo.oa.modules.security.entity.SystemUser;
import com.useeinfo.oa.modules.security.util.SessionKeyUtils;
import com.useeinfo.oa.open.admin.DictInfoManagerAction;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
import java.util.*;

/**
 * @Auther: xudong.sun
 * @Date: 2018/12/5 09:34
 * @Description:
 */
@Controller
@RequestMapping("/web/admin/repairOrder")
public class RepairOrderAdminAction {

    @Autowired
    private RepairOrderBiz repairOrderBiz;

    @Autowired
    private OrganizationBiz organizationBiz;

    @Autowired
    private DictInfoBiz dictInfoBiz;

    @Autowired
    private HttpServletRequest httpServletRequest;

    @Autowired
    private AreaBiz areaBiz;

    @Autowired
    private EnterpriseBiz enterpriseBiz;

    @Autowired
    private FacilityBiz facilityBiz;

    @Autowired
    private SystemUserBiz systemUserBiz;

    @Autowired
    private RepairOrderLogBiz repairOrderLogBiz;

    @Autowired
    private ResourceBiz resourceBiz;

    @Autowired
    private SystemUserOrganizationBiz systemUserOrganizationBiz;

    @Autowired
    private AuditNodeBiz auditNodeBiz;

    @Autowired
    private AuditFlowBiz auditFlowBiz;

    @Autowired
    private PositionBiz positionBiz;
    @Autowired
    private RepairLevelBiz repairLevelBiz;
    @Autowired
    private TroubleCatBiz troubleCatBiz;

    @Autowired
    private CustomerRepairBiz customerRepairBiz;

    /**
     * 打开列表页面
     */
    @RequestMapping("/list")
    public ModelAndView list(HttpServletRequest request) {
        ModelAndView modelAndView = new ModelAndView();
        Enterprise enterprise=SessionKeyUtils.getSessionEnterprise(request);
        List<Enterprise>enterpriseList=enterpriseBiz.findList(new QueryParam("-1","-1"));
        modelAndView.addObject("enterprise", enterprise);
        modelAndView.addObject("enterprises", enterpriseList);
        modelAndView.setViewName("pages/admin/repairOrder/list");
        return modelAndView;
    }


    /**
     * 查询列表
     */
    @RequestMapping("/listJson")
    @ResponseBody
    public JSONObject listJson(@RequestParam(value = "pageNo", required = false) String pageNowParam,
                               @RequestParam(value = "pageSize", required = false) String pageSizeParam,
                               @RequestParam(value = "reportCode", required = false) String reportCode,
                               @RequestParam(value = "orderStatus", required = false) String orderStatus,
                               @RequestParam(value = "reportContent", required = false) String reportContent,
                               @RequestParam(value = "reportType", required = false) String reportType,
                               @RequestParam(value = "reportUser", required = false) String reportUser,
                               @RequestParam(value = "createDate1", required = false) String createDate1,
                               @RequestParam(value = "reportArea", required = false) String reportArea,
                               @RequestParam(value = "createDate2", required = false) String createDate2,
                               @RequestParam(value = "customerName", required = false) String customer,
                               @RequestParam(value = "call", required = false) String callNumber,
                               @RequestParam(value = "repairType", required = false) String repairType,
                               @RequestParam(value = "belongEnterprise", required = false) String belongEnterprise,
                               @RequestParam(value = "orderBy", required = false) String orderBy,
                               HttpServletRequest request
    ) {
        Enterprise enterprise = SessionKeyUtils.getSessionEnterprise(request);
        SystemUser sessionUser = SessionKeyUtils.getSessionUser(request);
        QueryParam queryParam = new QueryParam(pageNowParam, pageSizeParam);


        if (StringUtils.isNotBlank(orderStatus)) {
            queryParam.getSqlMap().put("repairOrderStatus", orderStatus);
        }
        if (StringUtils.isNotBlank(reportContent)) {
            queryParam.getSqlMap().put("reportContent", reportContent);
        }

        if (StringUtils.isNotBlank(createDate1)) {
            queryParam.getSqlMap().put("createDate1", createDate1);
        }
        if (StringUtils.isNotBlank(reportArea)) {
            queryParam.getSqlMap().put("reportArea", reportArea);
        }
        if (StringUtils.isNotBlank(reportType)) {
            queryParam.getSqlMap().put("repairOrderTypeEnum", reportType);
        }else{
            queryParam.getSqlMap().put("AUTOMATIC_REPAIR", "AUTOMATIC_REPAIR");
        }
        if (StringUtils.isNotBlank(reportUser)) {
            queryParam.getSqlMap().put("reportUser", reportUser);
        }
        if (StringUtils.isNotBlank(createDate2)) {
            queryParam.getSqlMap().put("createDate2", createDate2);
        }
        if (StringUtils.isNotBlank(callNumber)) {
            queryParam.getSqlMap().put("callNumber", callNumber);
        }
        if (StringUtils.isNotBlank(customer)) {
            queryParam.getSqlMap().put("customer", customer);
        }
        if (StringUtils.isNotBlank(repairType)) {
            queryParam.getSqlMap().put("repairType", repairType);
        }
//        queryParam.getSqlMap().put("repairSource", "CUSTOMER_REPORT");

        if(enterprise.getEnterpriseName().equals("400center")){
            queryParam.getSqlMap().put("repairOrderTypeEnum", "_400_ORDER");
            queryParam.getSqlMap().put("enterpriseId", belongEnterprise);
        }else{
            if (enterprise != null) {
                queryParam.getSqlMap().put("enterpriseId", enterprise.getId() + "");
            }
        }
        queryParam.getSqlMap().put("reportCode", reportCode);
        if (StringUtils.isNotBlank(orderBy)) {
            queryParam.setSqlOrder("order by " + orderBy);
        }
        return repairOrderBiz.findJSONList(queryParam);
    }

    /**
     * 日志页面
     */
    @RequestMapping("/logPage")
    public ModelAndView logListJson(String id, HttpServletRequest request) {
        Enterprise enterprise = SessionKeyUtils.getSessionEnterprise(request);
        QueryParam queryParam = new QueryParam();
        queryParam.getSqlMap().put("repairOrderId", id);
        if (enterprise != null) {
            queryParam.getSqlMap().put("enterpriseId", enterprise.getId() + "");
        }
        queryParam.setSqlOrder(" order by id ");
        List<RepairOrderLog> repairOrderLogs = repairOrderLogBiz.findList(queryParam);
        ModelAndView modelAndView = new ModelAndView();
        modelAndView.setViewName("pages/admin/repairOrder/log");
        modelAndView.addObject("repairOrderLogs", repairOrderLogs);
        return modelAndView;
    }


    /**
     * 获取编辑页面
     */
    @RequestMapping("/editPage")
    public ModelAndView getEditPage(@RequestParam(value = "id", required = false) String repairOrderParam) {
        SystemUser systemUser = SessionKeyUtils.getSessionUser(httpServletRequest);
        Enterprise sessionEnterprise = SessionKeyUtils.getSessionEnterprise(httpServletRequest);
        ModelAndView modelAndView = new ModelAndView();
        RepairOrder repairOrder = null;
        String img1 = "";
        String img2 = "";
        String img3 = "";
        String img4 = "";
        String img5 = "";
        if (StringUtils.isNotBlank(repairOrderParam)) {
            repairOrder = repairOrderBiz.findModel(StringConverters.null2Long(repairOrderParam));
            if (repairOrder.getReportPhoto() != null && repairOrder.getReportPhoto().size() != 0) {
                List<Resource> resources = new ArrayList<>(repairOrder.getReportPhoto());
                resources.sort((o1, o2) -> o1.getId() < o2.getId() ? -1 : 1);
                img1 = Configuration.getConfigurationByName("hostUrl") + resources.get(0).getPath();
                if (resources.size() > 1) {
                    img2 = Configuration.getConfigurationByName("hostUrl") + resources.get(1).getPath();
                }
                if (resources.size() > 2) {
                    img3 = Configuration.getConfigurationByName("hostUrl") + resources.get(2).getPath();
                }
                if (resources.size() > 3) {
                    img4 = Configuration.getConfigurationByName("hostUrl") + resources.get(3).getPath();
                }
                if (resources.size() > 4) {
                    img5 = Configuration.getConfigurationByName("hostUrl") + resources.get(4).getPath();
                }
            }

            if (repairOrder.getRepairOrderTypeEnum().getCode() == "_400_ORDER" ||
                    repairOrder.getRepairOrderTypeEnum().getCode().equals("_400_ORDER") ) {
                modelAndView.addObject("repairOrderType", "_400_ORDER");
            } else {
                modelAndView.addObject("repairOrderType", "COMMON_ORDER");
            }

        } else {
            modelAndView.addObject("repairOrderType", "COMMON_ORDER");
            repairOrder = new RepairOrder();
            repairOrder.setReportUser(systemUser);
            QueryParam systemUserOrganizationParam = new QueryParam();
            if (sessionEnterprise != null) {
                systemUserOrganizationParam.getSqlMap().put("enterpriseId", StringConverters.null2String(sessionEnterprise.getId()));
            }
            systemUserOrganizationParam.getSqlMap().put("systemUserId", StringConverters.null2String(systemUser.getId()));
            List<SystemUserOrganization> systemUserOrganizations = systemUserOrganizationBiz.findList(systemUserOrganizationParam);
            if (CollectionUtils.isNotEmpty(systemUserOrganizations)) {
                repairOrder.setOrganization(systemUserOrganizations.get(0).getOrganization());
            }
        }
        String signEnterpriseId=Configuration.getConfigurationByName("signEnterpriseId");
        modelAndView.addObject("signEnterpriseId",signEnterpriseId);
        modelAndView.setViewName("pages/admin/repairOrder/edit");
        if(repairOrder.getId()==null){
            repairOrder.setInRoutingScope(true);
        }
        modelAndView.addObject("repairOrder", repairOrder);
        if(StringUtils.isNotBlank(repairOrder.getRecordingPath())){
           QueryParam queryParam = new QueryParam();
           queryParam.getSqlMap().put("recordPath",repairOrder.getRecordingPath());
            List<CustomerRepair> customerRepairs = customerRepairBiz.findList(queryParam);
            if(CollectionUtils.isNotEmpty(customerRepairs)){
                modelAndView.addObject("recording",DateTimeUtils.format(customerRepairs.get(0).getCallDate(),"yyyy-MM-dd HH:mm:ss") + "的录音");
            }
        }
        if (sessionEnterprise != null) {
            modelAndView.addObject("enterprise", sessionEnterprise);
        }
        modelAndView.addObject("img1", img1);
        modelAndView.addObject("img2", img2);
        modelAndView.addObject("img3", img3);
        modelAndView.addObject("img4", img4);
        modelAndView.addObject("img5", img5);
        return modelAndView;
    }

    /**
     * ToDo 待对接
     * 获取编辑页面
     */
    @RequestMapping("/editPage400")
    public ModelAndView getEditPage400(@RequestParam(value = "id", required = false) String repairOrderParam) {

        RepairOrder repairOrder = null;
        if (StringUtils.isNotBlank(repairOrderParam)) {
            Long repairOrderId = StringConverters.ToLong(repairOrderParam);
            repairOrder = repairOrderBiz.findModel(repairOrderId);
        }
        ModelAndView modelAndView = new ModelAndView();
        modelAndView.setViewName("pages/admin/repairOrder/edit400");
        modelAndView.addObject("repairOrder", repairOrder);
        return modelAndView;
    }

    @RequestMapping("/detail")
    public ModelAndView detail(String id) {
        ModelAndView modelAndView = new ModelAndView();
        RepairOrder repairOrder = repairOrderBiz.findModel(StringConverters.null2Long(id));
        modelAndView.addObject("repairOrder", repairOrder);
        modelAndView.addObject("repairOrderType", repairOrder.getRepairOrderTypeEnum().getName());

        if(StringUtils.isNotBlank(repairOrder.getRecordingPath())){
            modelAndView.addObject("recordPath",Configuration.getConfigurationByName("recordUrl") + repairOrder.getRecordingPath());
        }
        List<SelectVO> list = new ArrayList<>();
        if (StringUtils.isNotBlank(repairOrder.getFlow())) {
            JSONArray jsonArray = JSONArray.parseArray(repairOrder.getFlow());
            if (jsonArray.size() > 0) {
                for (int i = 0; i < jsonArray.size(); i++) {
                    JSONObject j = jsonArray.getJSONObject(i);
                    SelectVO selectVO = new SelectVO();
                    Long organizationId = AliJsonObjectCover.ObjectLong(j, "organizationId");
                    if (organizationId == null) {
                        selectVO.setText("");
                    } else {
                        selectVO.setText(organizationBiz.findModel(StringConverters.null2Long(organizationId)).getOrganizationName());
                    }
                    Long relationId = AliJsonObjectCover.ObjectLong(j, "relationId");
                    String nodeTypeEnum = AliJsonObjectCover.ObjectString(j, "nodeTypeEnum");
                    if ("POSITION".equals(nodeTypeEnum)) {
                        selectVO.setValue("岗位 " + positionBiz.findModel(StringConverters.null2Long(relationId)).getName());
                    } else if ("USER".equals(nodeTypeEnum)) {
                        selectVO.setValue("用户 " + systemUserBiz.findModel(StringConverters.null2Long(relationId)).getUserName());
                    } else if ("SELF".equals(nodeTypeEnum)) {
                        selectVO.setValue("接单人 " + repairOrder.getReportUser().getUserName());
                    }
                    list.add(selectVO);
                }
            }
        }
        modelAndView.addObject("flow", list);
        modelAndView.setViewName("pages/admin/repairOrder/detail");
        return modelAndView;
    }


    /**
     * 保存操作
     *
     * @param repairOrder
     * @return
     */
    @RequestMapping( "/addOrUpdate")
    @ResponseBody
    public ResultDto addOrUpdate(RepairOrder repairOrder,
                                 @RequestParam(value = "selectSrc[]",required = false) String selectSrc,
                                 @RequestParam(value = "selectRecordingPath[]",required = false) String selectRecordingPath,
                                 @RequestParam(value = "repairOrderType", required = false) String reportType,
                                 @RequestParam(value = "createDate1", required = false) String createDate,
                                 @RequestParam(value = "majorName", required = false) String majorName,
                                 @RequestParam(value = "repairFinishTime1", required = false) String repairFinishTime1,
                                 @RequestParam(value = "presenceTime1", required = false) String presenceTime1,
                                 @RequestParam(value = "selectFacilityId[]", required = false) String selectFacilityId,
                                 @RequestParam(value = "selectAreaId[]", required = false) String selectAreaId,
                                 @RequestParam(value = "selectUserId[]", required = false) String selectUserId,
                                 @RequestParam(value = "recording", required = false) String recording,
                                 @RequestParam(value = "troubleCatId", required = false) String troubleCatId,
                                 @RequestParam(value = "receiveUserId", required = false) String receiveUserId,
                                 @RequestParam(value = "chargeUserId", required = false) String chargeUserId,
                                 @RequestParam(value = "telephoneUserId", required = false) String telephoneUserId,
                                 @RequestParam(value = "repairOrderStatusEnum", required = false) String repairOrderStatusEnum,
                                 @RequestParam(value = "selectRepairTypeId[]", required = false) String selectRepairTypeId,
                                 @RequestParam(value = "selectReportLevelId[]", required = false) String selectReportLevelId,
                                 @RequestParam(value = "selectOrganizationId[]", required = false) String selectOrganizationId,
                                 @RequestParam(value = "selectCompleteAuditFlowId[]", required = false) String selectCompleteAuditFlowId,
                                 @RequestParam(value = "selectRepairEnterpriseId[]", required = false) String selectRepairEnterpriseId,
                                 @RequestParam(value = "sImg1", required = false) String sImg1,
                                 @RequestParam(value = "sImg2", required = false) String sImg2,
                                 @RequestParam(value = "sImg3", required = false) String sImg3,
                                 @RequestParam(value = "sImg4", required = false) String sImg4,
                                 @RequestParam(value = "sImg5", required = false) String sImg5,
                                 @RequestParam(value = "pic1", required = false) MultipartFile pic1,
                                 @RequestParam(value = "pic2", required = false) MultipartFile pic2,
                                 @RequestParam(value = "pic3", required = false) MultipartFile pic3,
                                 @RequestParam(value = "pic4", required = false) MultipartFile pic4,
                                 @RequestParam(value = "pic5", required = false) MultipartFile pic5,
                                 @RequestParam(value = "position", required = false) String position,
                                 @RequestParam(value = "selectTelephoneUser[]", required = false) String selectTelephoneUser


                                 ) {
        SystemUser systemUser=SessionKeyUtils.getSessionUser(httpServletRequest);
        return repairOrderBiz.addRepairPC(repairOrder, reportType, createDate, majorName, repairFinishTime1, presenceTime1, selectFacilityId, selectAreaId, selectUserId, recording, troubleCatId, receiveUserId, chargeUserId, telephoneUserId, repairOrderStatusEnum, selectRepairTypeId, selectReportLevelId, selectOrganizationId, selectCompleteAuditFlowId, sImg1, sImg2, sImg3, sImg4, sImg5, pic1, pic2, pic3, pic4, pic5, selectRepairEnterpriseId,selectSrc,selectRecordingPath, position,systemUser,selectTelephoneUser);
    }

    /**
     * 删除维修单
     *
     * @param id
     * @return
     */
    @RequestMapping("/delete")
    @ResponseBody
    public ResultDto delete(String id) {
        repairOrderBiz.deleteLogic(repairOrderBiz.findModel(StringConverters.null2Long(id)));
        return ResultUtil.success();
    }

    /**
     * 指定接单人列表跳转页
     *
     * @param repairOrderId
     * @return
     */
    @RequestMapping("/assignUser")
    public ModelAndView assignUser(String repairOrderId) {
        ModelAndView modelAndView = new ModelAndView();
        modelAndView.addObject("repairId", repairOrderId);
        modelAndView.setViewName("pages/admin/repairOrder/assignUser");
        return modelAndView;
    }

    /**
     * 指定岗位列表跳转页
     *
     * @param repairOrderId
     * @return
     */
    @RequestMapping("/assignPosition")
    public ModelAndView assignPosition(String repairOrderId) {
        ModelAndView modelAndView = new ModelAndView();
        modelAndView.addObject("repairId", repairOrderId);
        modelAndView.setViewName("pages/admin/repairOrder/assignPosition");
        return modelAndView;
    }

    //指定人员json数据
    @RequestMapping("/getUserByArea")
    @ResponseBody
    public JSONObject getUserByArea(String repairId, HttpServletRequest request,
                                    @RequestParam(value = "pageNo", required = false) String pageNowParam,
                                    @RequestParam(value = "pageSize", required = false) String pageSizeParam) {
        RepairOrder repairOrder = repairOrderBiz.findModel(StringConverters.null2Long(repairId));

        String authorityName = Configuration.getConfigurationByName("repairAuthorityName");

        return systemUserBiz.getSystemUserJson(repairOrder.getReportArea() == null ? null : repairOrder.getReportArea().getId() + "", repairOrder.getEnterprise().getId() + "", authorityName, pageNowParam, pageSizeParam,repairOrder.getEnterprise());
    }

    //指定岗位json数据
    @RequestMapping("/getPositionByArea")
    @ResponseBody
    public JSONObject getPositionByArea(String repairId, HttpServletRequest request,
                                        @RequestParam(value = "pageNo", required = false) String pageNowParam,
                                        @RequestParam(value = "pageSize", required = false) String pageSizeParam) {
        RepairOrder repairOrder = repairOrderBiz.findModel(StringConverters.null2Long(repairId));
        String authorityName = Configuration.getConfigurationByName("repairAuthorityName");
        return positionBiz.getPositionJson(repairOrder.getReportArea() == null ? null : repairOrder.getReportArea().getId() + "", repairOrder.getEnterprise().getId() + "", authorityName, pageNowParam, pageSizeParam);
    }


    /**
     * 保存指定人
     *
     * @param assignIds
     * @param repairId
     * @return
     */
    @RequestMapping("/saveAssignList")
    @ResponseBody
    public ResultDto saveAssignList(String assignIds, String repairId, HttpServletRequest request) {
        Enterprise enterprise = SessionKeyUtils.getSessionEnterprise(request);
        SystemUser sessionUser = SessionKeyUtils.getSessionUser(request);
        JSONArray jsonArray = JSONArray.parseArray(assignIds);
        RepairOrder repairOrder = repairOrderBiz.findModel(StringConverters.null2Long(repairId));
        Set<SystemUser> systemUsers = repairOrder.getAssignUsers();
        if (systemUsers == null) {
            systemUsers = new HashSet<>();
        }
        for (Object id : jsonArray) {
            SystemUser systemUser = systemUserBiz.findModel(StringConverters.null2Long(id));
            if (systemUser != null) {
                systemUsers.add(systemUser);
            }
        }
        repairOrder.setAssignTypeEnum(AssignTypeEnum.USER);
        repairOrder.setAssign(Boolean.TRUE);
        repairOrder.setAssignUsers(systemUsers);
        repairOrderBiz.addOrUpdate(repairOrder);
        repairOrderLogBiz.addLog(repairOrder, sessionUser, RepairOrderLogOperationEnum.ASSIGN_USER, enterprise, null);
        return ResultUtil.success();
    }

    /**
     * 保存指定岗位数据
     *
     * @param assignIds
     * @param repairId
     * @return
     */
    @RequestMapping("/saveAssignPosition")
    @ResponseBody
    public ResultDto saveAssignPosition(String assignIds, String repairId, HttpServletRequest request) {
        Enterprise enterprise = SessionKeyUtils.getSessionEnterprise(request);
        SystemUser sessionUser = SessionKeyUtils.getSessionUser(request);
        JSONArray jsonArray = JSONArray.parseArray(assignIds);
        RepairOrder repairOrder = repairOrderBiz.findModel(StringConverters.null2Long(repairId));
        Set<Position> positions = repairOrder.getAssignPositions();
        if (positions == null) {
            positions = new HashSet<>();
        }
        for (Object id : jsonArray) {
            Position position = positionBiz.findModel(StringConverters.null2Long(id));
            if (positions != null) {
                positions.add(position);
            }
        }
        repairOrder.setAssign(Boolean.TRUE);
        repairOrder.setAssignTypeEnum(AssignTypeEnum.POSITION);
        repairOrder.setAssignPositions(positions);
        repairOrderBiz.addOrUpdate(repairOrder);
        repairOrderLogBiz.addLog(repairOrder, sessionUser, RepairOrderLogOperationEnum.ASSIGN_POSITION, enterprise, null);
        return ResultUtil.success();
    }


    /**
     * 紧急程度下拉选择
     */

    @RequestMapping("/getRepairLevelListMagic")
    @ResponseBody
    public List<SelectVO> getRepairLevelListMagic(@RequestParam(value = "q", required = false) String q,
                                                  @RequestParam(value = "id", required = false) String id,
                                                  HttpServletRequest request
    ) {
        Enterprise enterprise = SessionKeyUtils.getSessionEnterprise(request);
        List<SelectVO> selectVOS = new ArrayList<>();
        RepairLevel repairLevel = repairLevelBiz.findModel(StringConverters.ToLong(id));
        if (repairLevel != null) {
            selectVOS.add(new SelectVO(repairLevel.getGrade(), repairLevel.getId() + ""));
        }
        QueryParam queryParam = new QueryParam(1, 20);
        if (enterprise != null) {
            queryParam.getSqlMap().put("enterpriseId", enterprise.getId() + "");
        }
        queryParam.getSqlMap().put("magicLike", q);
        queryParam.getSqlMap().put("magicId", id);
        queryParam.getSqlMap().put("enterpriseId", enterprise.getId() + "");
        List<RepairLevel> repairLevelList = repairLevelBiz.findList(queryParam);
        repairLevelList.forEach(repairLevel1 -> selectVOS.add(new SelectVO(repairLevel1.getGrade(), repairLevel1.getId() + "")));
        return selectVOS;
    }


    /**
     * 维修导出
     */
    @RequestMapping(value = "/exportOrder", produces = {"text/plain;charset=UTF-8"})
    @ResponseBody
    public void repairOrderExport(HttpServletResponse response, HttpServletRequest request) {
        String orderStatus = "";
        String reportCode = "";
        String reportContent = "";
        String createDate1 = "";
        String createDate2 = "";
        String reportArea = "";
        String reportUser = "";
        String reportType = "";
        String callNumber = "";
        String customer = "";
        String belongEnterprise = "";
        String repairType = "";

        try {
            reportCode = URLDecoder.decode(request.getParameter("reportCode"), "UTF-8");
            orderStatus = URLDecoder.decode(request.getParameter("orderStatus"), "UTF-8");
            reportContent = URLDecoder.decode(request.getParameter("reportContent"), "UTF-8");
            createDate1 = URLDecoder.decode(request.getParameter("createDate1"), "UTF-8");
            createDate2 = URLDecoder.decode(request.getParameter("createDate2"), "UTF-8");
            reportArea = URLDecoder.decode(request.getParameter("reportArea"), "UTF-8");
            reportUser = URLDecoder.decode(request.getParameter("reportUser"), "UTF-8");
            reportType = URLDecoder.decode(request.getParameter("reportType"), "UTF-8");
            callNumber = URLDecoder.decode(request.getParameter("callNumber"), "UTF-8");
            customer = URLDecoder.decode(request.getParameter("customer"), "UTF-8");
            belongEnterprise = URLDecoder.decode(request.getParameter("belongEnterprise"), "UTF-8");
            repairType = URLDecoder.decode(request.getParameter("repairType"), "UTF-8");

        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
        QueryParam queryParam = new QueryParam();
        Enterprise enterprise = SessionKeyUtils.getSessionEnterprise(request);
        if(enterprise.getEnterpriseName().equals("400center")){
            queryParam.getSqlMap().put("repairOrderTypeEnum", "_400_ORDER");
            queryParam.getSqlMap().put("enterpriseId", belongEnterprise);
        }else{
            if (enterprise != null) {
                queryParam.getSqlMap().put("enterpriseId", enterprise.getId() + "");
            }
            if (StringUtils.isNotBlank(reportType)) {
                queryParam.getSqlMap().put("repairOrderTypeEnum", reportType);
            }else{
                queryParam.getSqlMap().put("AUTOMATIC_REPAIR", "AUTOMATIC_REPAIR");
            }
        }
        queryParam.getSqlMap().put("reportCode", reportCode);
        queryParam.getSqlMap().put("repairOrderStatus", orderStatus);
        queryParam.getSqlMap().put("reportContent", reportContent);
        queryParam.getSqlMap().put("reportArea", reportArea);
        if (StringUtils.isNotBlank(callNumber)) {
            queryParam.getSqlMap().put("callNumber", callNumber);
        }
        if (StringUtils.isNotBlank(repairType)) {
            queryParam.getSqlMap().put("repairType", repairType);
        }
        if (StringUtils.isNotBlank(customer)) {
            queryParam.getSqlMap().put("customer", customer);
        }
        if(StringUtils.isNotBlank(createDate1)){
            queryParam.getSqlMap().put("createDate1", createDate1);
        }
        if(StringUtils.isNotBlank(createDate2)){
            queryParam.getSqlMap().put("createDate2", createDate2);
        }
        if (StringUtils.isNotBlank(reportUser)) {
            queryParam.getSqlMap().put("reportUser", reportUser);
        }
        queryParam.getSqlMap().put("repairOrderStatus", orderStatus);
        JSONArray jsonArray = new JSONArray();
        List<RepairOrder> repairOrders = repairOrderBiz.findList(queryParam);

        for (RepairOrder repairOrder : repairOrders) {
            //审核时间
            QueryParam queryParam1=new QueryParam();
            queryParam1.getSqlMap().put("repairOrderLogOperationEnum","AUDIT");
            queryParam1.getSqlMap().put("repairOrderId",repairOrder.getId().toString());
            List<RepairOrderLog> repairOrderLogs=repairOrderLogBiz.findList(queryParam1);
            String time="";
            if(CollectionUtils.isNotEmpty(repairOrderLogs)){
                time=DateTimeUtils.formatDateToStringWithTime(repairOrderLogs.get(0).getCreateDate());
            }
           JSONObject jsonObject= repairOrder.toJSONObject();
            jsonObject. put("auditTime",time);
            jsonArray.add(jsonObject);
        }
        try {
            ExcelExport.exportExcelFile("维修清单", ExcelExportMap.REPAIR_ORDER_LIST_EXPORT_MAP(), jsonArray, response);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * DashBoard评价统计
     */
    @RequestMapping("/countScore")
    @ResponseBody
    public JSONObject countScore(String enterpriseId, String systemUserId) {
        return repairOrderBiz.countScore(enterpriseId, systemUserId);
    }


    /**
     * 获取系统模块选择数据
     *
     * @param q
     * @return
     */
    @RequestMapping("/getSrcSelect")
    @ResponseBody
    public List<SelectVO> getSrcSelect(@RequestParam(value = "q", required = false) String q,
                                       @RequestParam(value = "id", required = false) String id) {

        return customerRepairBiz.getCustomerRepairs(id, q);
    }

    @RequestMapping("/getRecordingPath")
    @ResponseBody
    public List<SelectVO> getRecordingPath(@RequestParam(value = "id", required = false) String id, @RequestParam(value = "src", required = false) String src) {
        List<SelectVO> selectVOS = new ArrayList<>();
        QueryParam queryParam = new QueryParam();
        if (StringUtils.isNotBlank(src)) {
            queryParam.getSqlMap().put("src", src);
        }
        queryParam.getSqlMap().put("deleteStatus", "false");
        queryParam.getSqlMap().put("magicId",id);
        List<CustomerRepair> list = customerRepairBiz.findList(queryParam);
        for (CustomerRepair customerRepair : list) {
            selectVOS.add(new SelectVO(DateTimeUtils.format(customerRepair.getCallDate(),"yyyy-MM-dd HH:mm:ss") + "的录音",StringConverters.null2String(customerRepair.getRecordPath())));
        }
        return selectVOS;
    }

}
